package com.baidu.bulls.stock.trade.oauth.config;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;

/**
 * description: web访问配置，哪些放行，哪些限制
 */

@Primary
@Order(90)
@Configuration
@EnableWebSecurity
//web访问配置
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    /**
     * 用户服务接口
     */
    @Autowired
    private UserDetailsService authStockUserDetailService;

    /**
     * 密码编码器（支持加密处理）
     */
    @Autowired
    private StockPasswordEncoder stockPasswordEncoder;


    /**
     * Web服务认证配置
     * @param http
     */
    @Override
    @SneakyThrows //异常抛出处理
    protected void configure(HttpSecurity http) {
        http.formLogin()
                .loginPage("/token/login")  //登录界面
                .loginProcessingUrl("/token/form")  //登录处理接口
                .defaultSuccessUrl("/token/success") //登录成功
                .and()
                .authorizeRequests()
                .antMatchers(
                        "/token/**",
                        "/actuator/**",
                        "/druid/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable();
    }

    /**
     * 不拦截静态资源
     * @param web
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/css/**");
    }

    /**
     * 认证管理器
     * @return
     */
    @Bean
    @Override
    @SneakyThrows
    public AuthenticationManager authenticationManagerBean() {
        return super.authenticationManagerBean();
    }

    /**
     * 设置校验的实现方法还有密码的编码
     * @param auth
     * @throws Exception
     */
    @Autowired
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(authStockUserDetailService).passwordEncoder(stockPasswordEncoder);
    }
}
